const WebSocket = require('ws');
const BaiduAuth = require('./auth');
const config = require('../config/baidu');

class RealTimeASR {
  constructor() {
    this.auth = new BaiduAuth();
    this.ws = null;
    this.isConnected = false;
  }

  async connect() {
    try {
      const token = await this.auth.getAccessToken();
      const wsUrl = `${config.ASR_URL}?sn=${Date.now()}&appid=${config.APP_ID}&token=${token}`;
      
      this.ws = new WebSocket(wsUrl);
      
      this.ws.on('open', () => {
        console.log('WebSocket连接已建立');
        this.isConnected = true;
        this.sendStartMessage();
      });

      this.ws.on('message', (data) => {
        this.handleMessage(data);
      });

      this.ws.on('close', () => {
        console.log('WebSocket连接已关闭');
        this.isConnected = false;
      });

      this.ws.on('error', (error) => {
        console.error('WebSocket错误:', error);
      });

    } catch (error) {
      console.error('连接失败:', error);
    }
  }

  sendStartMessage() {
    const startMessage = {
      type: 'START',
      data: {
        appid: parseInt(config.APP_ID),
        appkey: config.API_KEY,
        dev_pid: 1537,
        cuid: 'node_client',
        sample: 16000,
        format: 'pcm'
      }
    };

    console.log('发送START消息:', JSON.stringify(startMessage, null, 2));
    this.ws.send(JSON.stringify(startMessage));
  }

  sendAudioData(audioBuffer) {
    if (this.isConnected && this.ws.readyState === WebSocket.OPEN) {
      const message = {
        type: 'DATA',
        data: {
          data: audioBuffer.toString('base64'),
          len: audioBuffer.length
        }
      };
      this.ws.send(JSON.stringify(message));
    }
  }

  sendFinishMessage() {
    if (this.isConnected) {
      const finishMessage = {
        type: 'FINISH'
      };
      this.ws.send(JSON.stringify(finishMessage));
    }
  }

  handleMessage(data) {
    try {
      const message = JSON.parse(data);
      console.log('收到ASR消息:', JSON.stringify(message, null, 2));

      if (message.type === 'MID_TEXT' || message.type === 'FIN_TEXT') {
        console.log('识别结果:', message.result);
        // 这里可以添加翻译逻辑
        this.onRecognitionResult(message.result, message.type);
      } else if (message.err_no !== undefined) {
        console.log('ASR错误:', message.err_msg || '未知错误', '错误码:', message.err_no);
      } else {
        console.log('其他ASR消息类型:', message.type);
      }
    } catch (error) {
      console.error('解析消息失败:', error);
      console.log('原始消息:', data.toString());
    }
  }

  onRecognitionResult(result, type) {
    // 可以在这里添加回调处理识别结果
    console.log(`[${type}] ${result}`);
  }

  disconnect() {
    if (this.ws) {
      this.sendFinishMessage();
      this.ws.close();
    }
  }
}

module.exports = RealTimeASR;